<template>
  <div v-if="editOpen" style="width: 100%;">
    <t-row style="align-items: stretch" :gutter="14">
      <t-col :span="12">
        <t-card class="step-card" size="small" title="内部项目">
          <t-table size="small" :loading="dataLoading" :selected-row-keys="selectedRowKeys"
                   @select-change="(val)=>{selectedRowKeys=val}" rowKey="id" :data="data" :columns="columns">
            <template #index="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
            <template #serviceName="{row}">
              <t-select :status="row.serviceIdStatus" @change="(val,content)=>{onServiceNameChange(val,content,row)}"
                        v-model="row.serviceId"
                        style="width: 240px;display: inline-block" filterable clearable
                        :keys="{label:'serviceName',value:'id'}" :options="serviceOptions">
                <div slot="tips" v-if="row.serviceIdStatus==='error'">不能为空</div>
              </t-select>
            </template>
            <template #businessName="{row}">
              <t-select  :disabled="!row.serviceId"  placeholder="请先选择子系统后搜索" :status="row.businessIdStatus" @change="(val,content)=>{onBusinessNameChange(val,content,row)}"
                         v-model="row.businessId"  @search="(search)=>{remoteProject(search,row)}" style="width: 390px;display: inline-block" filterable clearable
                         :keys="{label:'businessName',value:'businessId'}" :options="row.projectOptions">
                <div slot="tips" v-if="row.businessIdStatus==='error'">不能为空</div>
              </t-select>
            </template>
          </t-table>
          <div style="margin-top: 10px" class="btn-group-inline">
            <t-button v-if="data.length<=0 && data2.length<=0" @click="addData(1)">新增</t-button>
            <t-button @click="upData(1)">上移</t-button>
            <t-button @click="downData(1)">下移</t-button>
            <t-button @click="delData(1)">删除</t-button>
          </div>
        </t-card>
      </t-col>
    </t-row>
    <t-row style="align-items: stretch" :gutter="14">
      <t-col :span="12">
        <t-card class="step-card" size="small" title="外部项目">
          <t-table size="small" :loading="dataLoading" :selected-row-keys="selectedRowKeys2"
                   @select-change="(val)=>{selectedRowKeys2=val}" rowKey="id" :data="data2" :columns="columns2">
            <template #index="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
            <template #businessName="{row}">
              <t-input clearable :status="row.businessNameStatus"
                       @change="()=>{if(row.businessName!==''){row.businessNameStatus = 'default'}}"
                       style="width: 390px;display: inline-block" v-model="row.businessName">
                <div slot="tips" v-if="row.businessNameStatus==='error'">不能为空</div>
              </t-input>
            </template>
          </t-table>
          <div style="margin-top: 10px" class="btn-group-inline">
            <t-button v-if="data.length<=0 && data2.length<=0" @click="addData(2)">新增</t-button>
            <t-button @click="upData(2)">上移</t-button>
            <t-button @click="downData(2)">下移</t-button>
            <t-button @click="delData(2)">删除</t-button>
          </div>
        </t-card>
      </t-col>
    </t-row>
  </div>
  <div v-else style="width: 100%;">
    <t-row style="align-items: stretch" :gutter="14">
      <t-col :span="12">
        <t-card class="step-card" size="small" title="内部项目">
          <t-table size="small" :loading="dataLoading"  rowKey="id" :data="data" :columns="columns3">
            <template #index="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </t-table>
        </t-card>
      </t-col>
    </t-row>
    <t-row style="align-items: stretch" :gutter="14">
      <t-col :span="12">
        <t-card class="step-card" size="small" title="外部项目">
          <t-table size="small" :loading="dataLoading" rowKey="id" :data="data2" :columns="columns4">
            <template #index="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>

          </t-table>
        </t-card>
      </t-col>
    </t-row>
  </div>
</template>

<script>

export default {
  name: "awards-project",
  components: {},
  props: {
    value: Array,
    objId: [String, Number],
    editOpen: {
      type: Boolean,
      default: false
    },
    applyData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      companyLoading: false,
      companyOptions: [],
      serviceOptions: [],
      projectOptions: [],
      dataLoading: false,
      selectedRowKeys: [],
      selectedRowKeys2: [],
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        // {
        //   colKey: "isInnerCompany",
        //   title: "是否外部项目",
        //   width: 120,
        // },
        {
          colKey: "serviceName",
          title: "子系统名称",
          align: "center",
        },
        {
          colKey: "businessName",
          title: "项目名称",
          align: "center",
        },
      ],
      data2: [],
      columns2: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "businessName",
          title: "项目名称",
          align: "center",
        },
      ],
      columns3: [
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        // {
        //   colKey: "isInnerCompany",
        //   title: "是否外部项目",
        //   width: 120,
        // },
        {
          colKey: "serviceName",
          title: "子系统名称",
          align: "center",
        },
        {
          colKey: "businessName",
          title: "项目名称",
          align: "center",
        },
      ],
      columns4: [
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "businessName",
          title: "项目名称",
          align: "center",
        },
      ],
    }
  },
  watch: {
    objId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getCompanyList(val);
        }
      }
    },
    data: {
      deep: true,
      immediate: true,
      handler(val) {
        const newData = this.data.concat(this.data2).map((val, index) => ({...val, sort: index + 1}))
        this.$emit("input", newData);
      }
    },
    data2: {
      deep: true,
      immediate: true,
      handler(val) {
        const newData = this.data.concat(this.data2).map((val, index) => ({...val, sort: index + 1}))
        this.$emit("input", newData);
      }
    },
  },
  created() {
    this.getSysServices();
  },
  methods: {
    remoteProject(search,row){
      this.$api.cgzh.getProjectByServiceCode({
        serviceCode:row.serviceCode,
        projectName:search,
      }).then(response => {
        response.data.forEach(val2 => {
          const index = row.projectOptions.findIndex(val => val.businessId === val2.businessId)
          if (index === -1) {
            row.projectOptions.push(val2);
          }
        })
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onBusinessNameChange(val, content, row) {
      if (val) {
        row.businessName = content.option.businessName;
        row.businessIdStatus = 'default';
      } else {
        row.businessIdStatus = 'error';
      }
    },
    onServiceNameChange(val, content, row) {
      if (val) {
        row.serviceName = content.option.serviceName;
        row.serviceCode = content.option.serviceCode;
        row.serviceIdStatus = 'default';
      } else {
        row.serviceIdStatus = 'error';
      }
      row.projectOptions = [];
      // this.$api.cgzh.getProjectByServiceCode(content.option.serviceCode).then(response => {
      //   row.projectOptions = response.data;
      // }).catch((e) => {
      //   this.$message.error(e.toString());
      // });
    },
    getSysServices() {
      this.$api.cgzh.getSysServices().then(response => {
        this.serviceOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    checkData() {
      const isValidate = this.data.every((val, index) => {
        if (!val.serviceId) {
          this.$set(this.data[index], 'serviceIdStatus', 'error')
          this.$message.error(`内部项目：第${index + 1}条"子系统名称"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'serviceIdStatus', 'default')
        if (!val.businessId) {
          this.$set(this.data[index], 'businessIdStatus', 'error')
          this.$message.error(`内部项目：第${index + 1}条"项目名称"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'businessIdStatus', 'default')
        return true;
      });
      if (!isValidate) {
        return false
      }
      const isValidate2 = this.data2.every((val, index) => {
        if (!val.businessName) {
          this.$set(this.data2[index], 'businessNameStatus', 'error')
          this.$message.error(`外部项目：第${index + 1}条"项目名称"不能为空`);
          return false;
        }
        this.$set(this.data2[index], 'businessNameStatus', 'default')
        return true;
      });
      return isValidate2;
    },
    getCompanyList() {
      this.dataLoading = true;
      this.$api.cgzh.awards.projectListGet(this.objId).then(response => {
        const data = response.data.filter((val) => val.isInnerProject === '1')
        data.forEach((val,index)=>{
          data[index].projectOptions = [
            {
              businessId: val.businessId,
              businessName: val.businessName,
            }
          ]
        })
        this.data = data;
        // 如果拉不到数据且有默认数据则加入
        if(this.data.length<=0 && this.applyData.length>0){
          this.data = this.applyData;
        }
        this.data2 = response.data.filter((val) => val.isInnerProject === '0');
        this.dataLoading = false;
      }).catch((e) => {
        this.dataLoading = false;
        this.$message.error(e.toString());
      });
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
    addData(type) {
      if (type === 1) {
        this.data.push({
          id: Date.parse(new Date()),
          awardsId: this.objId,
          serviceId: null,
          serviceName: '',
          serviceCode: '',
          businessId: null,
          businessName: '',
          isInnerProject: '1',
          projectOptions: [],
        })
      } else {
        this.data2.push({
          id: Date.parse(new Date()),
          awardsId: this.objId,
          serviceId: null,
          serviceName: '',
          serviceCode: '',
          businessId: null,
          businessName: '',
          isInnerProject: '0',
          projectOptions: [],
        })
      }

    },
    upData(type) {
      if (type === 1) {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning("请选择一行");
          return;
        }
        if (this.data[0].id === this.selectedRowKeys[0]) {
          this.$message.warning("已是第一行");
        } else {
          const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
          this.moveInArray(this.data, index, index - 1)
        }
      } else {
        if (this.selectedRowKeys2.length <= 0) {
          this.$message.warning("请选择一行");
          return;
        }
        if (this.data2[0].id === this.selectedRowKeys2[0]) {
          this.$message.warning("已是第一行");
        } else {
          const index = this.data2.findIndex((val) => val.id === this.selectedRowKeys2[0])
          this.moveInArray(this.data2, index, index - 1)
        }
      }

    },
    downData(type) {
      if (type === 1) {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning("请选择一行");
          return;
        }
        if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
          this.$message.warning("已是最后一行");
        } else {
          const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
          this.moveInArray(this.data, index, index + 1)
        }
      } else {
        if (this.selectedRowKeys2.length <= 0) {
          this.$message.warning("请选择一行");
          return;
        }
        if (this.data2[this.data2.length - 1].id === this.selectedRowKeys2[0]) {
          this.$message.warning("已是最后一行");
        } else {
          const index = this.data2.findIndex((val) => val.id === this.selectedRowKeys2[0])
          this.moveInArray(this.data2, index, index + 1)
        }
      }

    },
    delData(type) {
      if (type === 1) {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning("请选择一行");
          return;
        }
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.data.splice(index, 1);
        this.selectedRowKeys = [];
      } else {
        if (this.selectedRowKeys2.length <= 0) {
          this.$message.warning("请选择一行");
          return;
        }
        const index = this.data2.findIndex((val) => val.id === this.selectedRowKeys2[0])
        this.data2.splice(index, 1);
        this.selectedRowKeys2 = [];
      }

    },
  }
}
</script>

<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>
